import router from "@/router";
import dynamicRouter from '@/router/routerList'
import { getUserInfo } from '@/utils/common.js';

/**
 * 国家级管理员 guo  省级管理员 sheng 市级管理员 shi
 * 县级管理员 xian 作业员 zyy 审核员 shy
 */
const rightTag = {
  'guo': '1',
  'sheng': '2',
  'shi': '2',
  'xian': '2',
  'zyy': '2',
  'shy': '2'
}

const state = {
  // 必须在store里保存一份菜单，store里的值刷新会重置，在router.beforeEach里作为判断条件。
  menu: []
}

const mutations = {
  setMenu(state, list) {
    state.menu = list
  }
}

const actions = {
  generateRoutes({ state }, role) {
    return new Promise((resolve, reject) => {
      let rolename = role ? role : getUserInfo().role
      if (!rolename) {
        resolve(null)
        return
      }
      // 动态路由不是一次性的添加，需要每次加载都做添加。也没法转成字符串缓存，不然router-view会不起作用
      let filteredRoutes = genAuthList(dynamicRouter, (it) => it.meta.premiList && it.meta.premiList.includes(rightTag[rolename]))
      filteredRoutes.forEach(item => {
        // router.addRoute 好像只能添加到一级路由上
        router.addRoute('views', item)
      })

      // // 缓存menus，menus值与routes值不同，routes里包含了隐藏的菜单
      // let filteredMenus = []
      // let menustr = sessionStorage.getItem('menus');
      // if (menustr) {
      //   filteredMenus = JSON.parse(menustr);
      // } else {
      //   let allmenu = JSON.parse(JSON.stringify(dynamicRouter))
      //   filteredMenus = genAuthList(allmenu, (it) => it.meta.premiList && it.meta.premiList.includes(rightTag[rolename]) && !it.meta.noMenuPage)
      //   sessionStorage.setItem('menus', JSON.stringify(filteredMenus));
      // }
      state.menu = filteredRoutes
      resolve(filteredRoutes)
    })
  },
}

//递归过滤菜单
const genAuthList = function (tree = [], validate = () => { }, arr = []) {
  if (!tree.length) return []
  for (let item of tree) {
    if (!validate.apply(null, [item])) continue
    let node = { ...item, children: [] }
    arr.push(node)
    if (item.children && item.children.length)
      genAuthList(item.children, validate, node.children)
  }
  return arr
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}